package cn.yueranzs.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.yueranzs.response.ResultCode;
import cn.yueranzs.response.UrlResultCode;
import cn.yueranzs.system.dto.useravatar.UserAvatarChangeDto;
import cn.yueranzs.system.pojo.User;
import cn.yueranzs.system.service.UserAvatarService;
import cn.yueranzs.system.service.UserService;
import cn.yueranzs.utils.AliyunOSSUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author yueranzs
 * @date 2021-11-16 14:50
 */
@Service
public class UserAvatarServiceImpl implements UserAvatarService {

    @Resource
    private UserService userService;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public JSONObject updateUserAvatar(UserAvatarChangeDto dto) {
        try {
            User user = userService.getById(dto.getId());
            //新增用户头像到OSS
            String filePath = AliyunOSSUtil.uploadFile(dto.getImgFile(), UrlResultCode.HEAD_PORTRAIT_URL.getMessage() + "/" + user.getId());
            //删除原来头像
            if (ObjectUtil.isNotEmpty(user.getAvatar())) {
                AliyunOSSUtil.deleteFile(user.getAvatar());
            }
            //修改用户头像
            user.setAvatar(filePath);
            user.setModifiedTime(DateUtil.date());
            userService.updateById(user);
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("avatarUrl",AliyunOSSUtil.getFileUrl(filePath,null));
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户头像
     *
     * @param username
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
    @Override
    public String getUserAvatar(String username) {
        User user = userService.getOne(new QueryWrapper<User>().lambda()
                .select(User::getAvatar)
                .eq(User::getDeleted, ResultCode.NODELETE.getCode())
                .eq(User::getUsername, username)
        );
        return ObjectUtil.isNotEmpty(user) ? user.getAvatar() : "";
    }
}
